package com.boxin.ims.modules.wechat.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.WechatConfig;
import com.boxin.ims.modules.wechat.entity.WechatMenu;
import com.boxin.ims.modules.wechat.service.WechatMenuService;

/**
 * 微信自定义菜单创建
 */
@Service
public class WechatMenuUtils implements ApplicationContextAware{
	
	public final static String BIND_MEMBER_KEY = "BIND_MEMBER_KEY"; 	//注册绑定会员事件 
	public final static String SIGN_MEMBER_KEY = "SIGN_MEMBER_KEY"; 	//签到绑定会员事件 
	public final static String LOTTERY_KEY = "LOTTERY_KEY"; 	//签到绑定会员事件 
	public final static String SCORE_EXCHANGE_KEY = "SCORE_EXCHANGE_KEY"; 	//签到绑定会员事件 
	public final static String SCORE_QUERY_KEY = "SCORE_QUERY_KEY"; 	//积分查询事件 
	
	private static WechatMenuService wechatMenuService;
	// http客户端
	public static DefaultHttpClient httpclient;
	
	static {
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端
	}

	public static void main(String[] args) {
		try {
			// 获取accessToken -参数appid，secret
			//String accessToken = getAccessToken("wxa089048968118e44", "8205df06d6b72e95e0c8e2bacce6c2a9");
			String accessToken = "zQztxLUM0ZIi1Wj74JQGV4DnUFPDY0OOCvVMzSfnFWQ16RmUcbGF4CxV1EoKPOxH_mYJ5DMd5BWzsRwmut24JiPgIBh1x269psBIpr1Eq0cBMlvTrLU29aHPg24cfouItFuW3anKRdK3FIPWVylbyQ";
			System.out.println(accessToken);
			String userInfo ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken;
			
			HttpPost httpost = HttpClientConnectionManager.getPostMethod(userInfo);
			httpost.setEntity(new StringEntity("{}", "UTF-8"));
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			System.out.println(jsonStr);
			JSONObject object = JSON.parseObject(jsonStr);
			
			
			// 创建菜单
			//String s = "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\":\"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查询\",\"key\":\"m_bus\"}]},{\"type\":\"click\",\"name\":\"关于企特\",\"key\":\"m_about\"}]}";
//			String s = "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\":\"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查询\",\"key\":\"m_bus\"},{\"type\":\"click\",\"name\":\"功能菜单\",\"key\":\"m_sysmenu\"}]},{\"name\":\"会员特权\",\"sub_button\":[{\"type\":\"click\",\"name\":\"签到\",\"key\":\"m_about\"},{\"type\":\"click\",\"name\":\"个人信息\",\"key\":\"m_imgmsg\"},{\"type\":\"click\",\"name\":\"音乐消息\",\"key\":\"m_musicmsg\"}]}]}";
//			//String res = createMenu(s, accessToken);
//			System.out.println(res);
//			WechatMenu menu1 = new WechatMenu();
//			menu1.setName("主菜单1");
//			menu1.setLevel(0);
//			menu1.setType("view");
//			menu1.setEventKey("Event_01");
//			List<WechatMenu> mainMenus1 = new ArrayList<WechatMenu>();
//			for(int i=0;i<5;i++){
//				WechatMenu menu = new WechatMenu();
//				menu.setName("子主菜单1-"+i);
//				menu.setLevel(1);
//				menu.setType("view");
//				menu.setEventKey("Event_01");
//				mainMenus1.add(menu);
//			}
//			menu1.setChildList(mainMenus1);
//			
//			
//			WechatMenu menu2 = new WechatMenu();
//			menu2.setName("主菜单2");
//			menu2.setLevel(0);
//			menu2.setType("view");
//			menu2.setEventKey("Event_01");
//			
//			
//			WechatMenu menu3 = new WechatMenu();
//			menu3.setName("主菜单2");
//			menu3.setLevel(0);
//			menu3.setType("view");
//			menu3.setEventKey("Event_01");
//			
//			List<WechatMenu> mainMenus = new ArrayList<WechatMenu>();
//			mainMenus.add(menu3);
//			mainMenus.add(menu2);
//			mainMenus.add(menu1);
//			
//			menuParams(mainMenus);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-15  下午11:44:39
	 * @function <p> 生成菜单 Key值  ：规则为 KEY_${userId}_${parentId}_${index}    (菜单顺序自上而下，自左而后) </p>
	 * @param wechatMenu
	 * @return
	 */
	public static String createMenuKey(WechatMenu wechatMenu){
		String eventKey = "KEY_userId_id_index_"+new Random().nextInt(9);
		
		String userId = wechatMenu.getUser().getId()+"";
		String id = wechatMenu.getId() +"";
		String index  = wechatMenu.getSort() + "";
		eventKey = eventKey.replaceAll("userId", userId);
		eventKey = eventKey.replaceAll("id", id);
		eventKey = eventKey.replaceAll("index", index);
		
		return eventKey;
	}
	
	
	/**
	 * 创建菜单
	 */
	public static String createMenu(String params, String accessToken) throws Exception {
		HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken);
		httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
		HttpResponse response = httpclient.execute(httpost);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(jsonStr);
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("errmsg");
	}

	/**
	 * 获取accessToken
	 */
	public static String getAccessToken(String appid, String secret) throws Exception {
		
//		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
//		HttpResponse response = httpclient.execute(get);
//		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
//		JSONObject object = JSON.parseObject(jsonStr);
//		return object.getString("access_token");
		
		
		//使用新的获取Token方式
		return TokenUtils.getAPIToken(appid, secret);
		
	}
	
	/**
	 * 查询菜单
	 */
	public static String getMenuInfo(String accessToken) throws Exception {
		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		return jsonStr;
	}
	
	/**
	 * 删除自定义菜单
	 */
	public static String getAccessToken(String accessToken) throws Exception {
		
		HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject object = JSON.parseObject(jsonStr);
		return object.getString("errmsg");
		
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-12  下午2:19:44
	 * @function <p> 生成菜单JSON </p>
	 * @param wechatMenus
	 * @return
	 */
	public static String menuParams(List<WechatMenu> wechatMenus){
		StringBuffer menuString = new StringBuffer();
		menuString.append("{\"button\":[").append("");
		for(WechatMenu menu : wechatMenus){
			if(menu.getLevel() == 0){
				List<WechatMenu> subMenus = menu.getChildList();
				if(subMenus!=null && subMenus.size()>0){
					
					menuString.append("{").append("");
					menuString.append("\"name\":\"").append(menu.getName()).append("\",").append("");
					menuString.append("\"sub_button\":[").append("");
					for(WechatMenu subMenu  :subMenus){
						menuString.append("{").append("");
						menuString.append("\"type\":\"").append(subMenu.getType()).append("\",").append("");
						menuString.append("\"name\":\"").append(subMenu.getName()).append("\",").append("");
						if("view".equals(subMenu.getType())){
							menuString.append("\"url\":\"").append(subMenu.getUrl()).append("\"");
						}else{
							menuString.append("\"key\":\"").append(subMenu.getEventKey()).append("\"");
						}
						menuString.append("},").append("");
					} 
					menuString.deleteCharAt(menuString.lastIndexOf(","));
					menuString.append("]}").append(",").append("");
				}else{
					menuString.append("{").append("");
					menuString.append("\"type\":\"").append(menu.getType()).append("\",").append("");
					menuString.append("\"name\":\"").append(menu.getName()).append("\",").append("");
					if("view".equals(menu.getType())){
						menuString.append("\"url\":\"").append(menu.getUrl()).append("\"");
					}else{
						menuString.append("\"key\":\"").append(menu.getEventKey()).append("\"");
					}
					menuString.append("}").append(",").append("");
				}
			}
		}
		menuString.deleteCharAt(menuString.lastIndexOf(","));
		menuString.append("]}");
		
		return menuString.toString();
	}
	
	
	public static List<WechatConfig> getPublicReplyList(){
		 List<WechatConfig> configs = new ArrayList<WechatConfig> ();
		WechatConfig config = new WechatConfig();
		config.setUpContent("注删会员");
		configs.add(config);
		
		return configs;
		
	}
	
	
	public static List<WechatMenu> getAllWechatMenus(){
		
		return null;
	}
	
	
	public static WechatMenu getWechatMenuByEventKey(String key ){
		return wechatMenuService.getByKey(key);
	}
	
	public static WechatMenu getWechatMenuByURL(String URL ){
		return wechatMenuService.getByURL(URL);
	}



	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		
		wechatMenuService	= (WechatMenuService)applicationContext.getBean("wechatMenuService");
		
	}
	
	
	
	
}